<template>
  <el-dialog title="更换手机号" :model-value="visible" @close="handleCancel" v-bind="$attrs">
    <el-form ref="formRef" :model="state.formData" :rules="state.rules">
      <el-form-item label="" prop="phone">
        <el-input v-model="state.formData.phone" placeholder="请输入手机号">
          <template #prepend>
            <el-select v-model="state.phonePrefix" placeholder="请选择" style="width: 140px">
              <el-option label="中国大陆 +86" value="86" />
              <el-option label="中国香港 +852" value="852" />
              <el-option label="中国澳门 +853" value="853" />
            </el-select>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="" prop="code">
        <send-code v-if="visible" v-model="state.formData.code" placeholder="请输入验证码" @send-code="handleSendCode"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button link @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, watch } from 'vue'
import SendCode from '@/components/SendCode.vue'

const formRef = ref(null)

const props = defineProps({
  phone: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:visible'])

const state = reactive({
  phonePrefix: '86',
  formData: {
    phone: props.phone,
    code: '',
  },
  rules: {
    phone: [
      {required: true, message: '请输入手机号'}
    ],
    code: [
      {required: true, message: '请输入验证码'}
    ]
  }
})

const handleSendCode = (done) => {
  done(true)
}

const handleCancel = () => {
  emits('update:visible', false)
}

const handleConfirm = () => {
  formRef.value.validate(valid => {
    if (!valid) {
      return 
    }
  })
}

watch(() => props.visible, (val) => {
  if (val) {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    state.formData.phone = props.phone
    state.formData.code = ''
  }
})

</script>